<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <div class="container mx-auto flex h-screen">
      <!-- 左侧导航 -->
      <div class="w-[280px] bg-white border-r border-gray-200 overflow-y-auto p-4">
        <div class="mb-4">
          <div class="relative">
            <el-input v-model="searchText" placeholder="搜索控制器" class="w-full !rounded-button" :prefix-icon="Search" />
          </div>
        </div>
        <div class="space-y-2">
          <div v-for="controller in filteredControllers" :key="controller.id" @click="selectController(controller)"
            :class="{
  'bg-blue-50 border-blue-500': currentController?.id === controller.id,
  'hover:bg-gray-50 border-transparent': currentController?.id !== controller.id
  }" class="p-3 border-l-4 cursor-pointer transition-all rounded-lg">
            <div class="font-medium">{{ controller.name }}</div>
            <div class="text-sm text-gray-500">{{ controller.englishName }}</div>
          </div>
        </div>
      </div>
      <!-- 右侧内容 -->
      <div class="flex-1 overflow-y-auto p-6">
        <template v-if="currentController">
          <!-- 控制器信息 -->
          <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
            <div class="flex flex-col">
              <div class="flex justify-between items-center mb-6 pb-4 border-b border-gray-100">
                <div class="flex items-center space-x-4">
                  <div>
                    <h1 class="text-2xl font-bold text-gray-900">{{ currentController.name }}</h1>
                    <div class="text-gray-500 mt-1">{{ currentController.englishName }}</div>
                    <el-tag size="small" type="info" class="ml-4">请求 ID: {{ currentController.requestId }}</el-tag>
                  </div>

                </div>
                <div class="flex space-x-3">
                  <el-button type="primary" :icon="Document" class="!rounded-button whitespace-nowrap"
                    @click="showProtoc">
                    查看 Protoc 协议
                  </el-button>
                  <el-button type="primary" :icon="Monitor" class="!rounded-button whitespace-nowrap"
                    @click="showCocos">
                    显示 Cocos 前端代码
                  </el-button>
                  <el-button type="primary" :icon="Connection" class="!rounded-button whitespace-nowrap"
                    @click="showRpcCall">
                    生成 RPC 调用接口
                  </el-button>
                </div>
              </div>
              <div class="text-gray-600 leading-relaxed max-w-3xl">{{ currentController.description }}</div>
            </div>
          </div>
          <!-- API 方法列表 -->
          <div class="space-y-4">
            <div v-for="method in currentController.methods" :key="method.id" class="bg-white rounded-lg shadow-sm mb-2.5">
              <el-collapse>
                <el-collapse-item>
                  <template #title>
                    <div class="py-2">
                      <div class="flex items-center space-x-4">
                        <h2 class="text-lg font-medium text-gray-900">【{{ method.name }}】</h2>
                        <div class="text-cyan-400 mr-2.5">{{ method.englishName }}</div>
                        <el-tag size="small" type="info" class="whitespace-nowrap">方法 ID: {{ method.id }}</el-tag>
                      </div>
                    </div>
                  </template>
                  <div class="p-6 pt-4 space-y-6">
                    <!-- 请求参数 -->
                    <div>
                      <h3 class="text-base font-medium mb-3 flex items-center text-gray-700">
                        <span class="mr-2">请求参数</span>
                      </h3>
                      <el-table :data="method.params" border class="w-full">
                        <el-table-column prop="name" label="参数名称" width="160" />
                        <el-table-column prop="type" label="类型" width="100" />
                        <el-table-column prop="javaType" label="Java类型" width="160" />
                        <el-table-column prop="description" label="描述" min-width="200" />
                      </el-table>
                      <div class="mt-4">
                        <h4 class="text-sm font-medium mb-2 text-gray-700">请求参数示例：</h4>
                        <pre
                          class="whitespace-pre-wrap bg-gray-50 p-4 rounded"><code>{{ JSON.stringify(JSON.parse(method.params[0].jsonExample), null, 2) }}</code></pre>
                      </div>
                    </div>
                    <!-- 返回值 -->
                    <div>
                      <h3 class="text-base font-medium mb-3 flex items-center text-gray-700">
                        <span class="mr-2">返回值</span>
                      </h3>
                      <el-table :data="method.returns" border class="w-full">
                        <el-table-column prop="name" label="字段名称" width="160" />
                        <el-table-column prop="type" label="类型" width="100" />
                        <el-table-column prop="javaType" label="Java类型" width="160" />
                        <el-table-column prop="description" label="描述" min-width="200" />
                      </el-table>
                      <div v-if="method.returns.length === 1 && method.returns[0].type === 'object'" class="mt-4">
                        <h4 class="text-sm font-medium mb-2 text-gray-700">返回值示例：</h4>
                        <pre
                          class="whitespace-pre-wrap bg-gray-50 p-4 rounded"><code>{{ JSON.stringify(JSON.parse(method.returns[0].jsonExample), null, 2) }}</code></pre>
                      </div>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </template>
        <div v-else class="h-full flex items-center justify-center text-gray-400">
          <el-empty description="请选择一个控制器" />
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <pre class="bg-gray-50 p-4 rounded-lg overflow-auto max-h-[600px]"><code>{{ dialogContent }}</code></pre>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { Search, Document, Monitor, Connection } from '@element-plus/icons-vue';
  interface Param {
    name: string;
    type: string;
    description: string;
    javaType: string;
    jsonExample: string;
  }
  interface Method {
    id: number;
    name: string;
    englishName: string;
    params: Param[];
    returns: Param[];
  }
  interface Controller {
    id: string;
    name: string;
    englishName: string;
    description: string;
    requestId: number;
    methods: Method[];
  }
  const searchText = ref('');
  const currentController = ref < Controller | null > (null);
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const dialogContent = ref('');
  const controllers: Controller[] = [
    {
      id: '1',
      name: '用户管理控制器',
      englishName: 'UserController',
      description: '处理用户相关的所有操作，包括用户认证、信息管理等',
      requestId: 1001,
      methods: [
        {
          id: 1,
          name: '用户登录',
          englishName: 'userLogin',
          params: [
            { name: 'loginRequest', type: 'object', javaType: 'LoginRequest', description: '登录请求对象', jsonExample: '{\n  "username": "john.doe",\n  "password": "password123"\n}' },
          ],
          returns: [
            { name: 'loginResponse', type: 'object', javaType: 'LoginResponse', description: '登录响应对象', jsonExample: '{\n  "token": "eyJhbGciOiJIUzI1NiJ9...",\n  "userId": 123456\n}' }
          ],
        },
        {
          id: 2,
          name: '获取用户信息',
          englishName: 'getUserInfo',
          params: [
            { name: 'userId', type: 'number', javaType: 'Long', description: '用户ID', jsonExample: '{\n  "userId": 123456\n}' },
          ],
          returns: [
            { name: 'userInfo', type: 'object', javaType: 'UserInfo', description: '用户信息对象', jsonExample: '{\n  "username": "john.doe",\n  "email": "john@example.com",\n  "role": "ADMIN"\n}' },
          ],
        },
      ],
    },
    {
      id: '2',
      name: '订单管理控制器',
      englishName: 'OrderController',
      description: '处理订单相关的所有操作，包括创建订单、查询订单等',
      requestId: 2001,
      methods: [
        {
          id: 3,
          name: '创建订单',
          englishName: 'createOrder',
          params: [
            { name: 'orderRequest', type: 'object', javaType: 'CreateOrderRequest', description: '创建订单请求对象', jsonExample: '{\n  "userId": 123456,\n  "products": [\n    {\n      "id": 1,\n      "quantity": 2,\n      "price": 99.99\n    }\n  ]\n}' },
          ],
          returns: [
            { name: 'orderInfo', type: 'object', javaType: 'OrderInfo', description: '订单信息对象', jsonExample: '{\n  "orderId": "ORD20230001",\n  "totalAmount": 299.99,\n  "status": "CREATED"\n}' },
          ],
        },
      ],
    },
  ];
  const filteredControllers = computed(() => {
    const filtered = controllers.filter(controller =>
      controller.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      controller.englishName.toLowerCase().includes(searchText.value.toLowerCase())
    );
    return filtered.sort((a, b) => a.requestId - b.requestId);
  });
  const selectController = (controller: Controller) => {
    currentController.value = controller;
  };
  const showProtoc = () => {
    dialogTitle.value = 'Protoc 协议';
    dialogContent.value = `
  syntax = "proto3";
  package user;
  service UserService {
  rpc Login (LoginRequest) returns (LoginResponse);
  rpc GetUserInfo (UserInfoRequest) returns (UserInfoResponse);
  }
  message LoginRequest {
  string username = 1;
  string password = 2;
  }
  message LoginResponse {
  string token = 1;
  int64 user_id = 2;
  }`;
    dialogVisible.value = true;
  };
  const showRpcCall = () => {
    if (!currentController.value) return;
    dialogTitle.value = 'RPC 调用接口示例';
    dialogContent.value = `
  // RPC 调用示例
  @Resource
  private ${currentController.value.englishName} ${currentController.value.englishName.charAt(0).toLowerCase() + currentController.value.englishName.slice(1)};
  // 方法调用示例
  ${currentController.value.methods.map(method => `
  public void ${method.englishName}Example() {
  // 请求参数构建
  ${method.params.map(param => `${param.javaType} ${param.name} = ${param.jsonExample};`).join('\n    ')}
  // 调用RPC接口
  ${method.returns.length > 0 ? `Response<${method.returns.length === 1 ? method.returns[0].javaType : 'Object'}> response = ` : ''}${currentController.value!.englishName.charAt(0).toLowerCase() + currentController.value.englishName.slice(1)}.${method.englishName}(${method.params.map(p => p.name).join(', ')});
  }
  `).join('\n')}`;
    dialogVisible.value = true;
  };
  const showCocos = () => {
    dialogTitle.value = 'Cocos 前端代码';
    dialogContent.value = `
  import { UserClient } from './generated/user_client';
  export class UserService {
  private client: UserClient;
  constructor() {
  this.client = new UserClient();
  }
  async login(username: string, password: string) {
  const request = { username, password };
  return await this.client.login(request);
  }
  async getUserInfo(userId: number) {
  const request = { userId };
  return await this.client.getUserInfo(request);
  }
  }`;
    dialogVisible.value = true;
  };
</script>
<style scoped>
  .el-input :deep(.el-input__wrapper) {
    border-radius: 8px;
  }

  pre {
    font-family: 'Fira Code', monospace;
    line-height: 1.6;
  }

  :deep(.el-collapse-item__header) {
    font-size: inherit;
    padding: 12px 20px;
  }

  :deep(.el-collapse-item__content) {
    padding: 0;
  }

  :deep(.el-table th) {
    background-color: #f8fafc;
    font-weight: 600;
  }

  :deep(.el-table--border) {
    border-radius: 8px;
    overflow: hidden;
  }

  :deep(.el-collapse) {
    border: none;
  }

  :deep(.el-collapse-item__wrap) {
    border: none;
  }

  :deep(.el-collapse-item__header) {
    border: none;
  }
  .method-title{
    background-color: grey;
  }
</style>